package com.rest.impl;

import org.scribe.model.Token;

import com.api.client.OAuthProvider;
import com.api.model.ApiConsumer;
import com.api.model.ApiEnvironment;
import com.api.model.ApiOAuth;
import com.api.model.ApiUser;
import com.rest.LoginRequest;
import com.rest.LoginService;
import com.rest.client.RestClientException;

public class LoginServiceImpl implements LoginService {

	@Override
	public ApiUser login(LoginRequest request) {

		try {

			ApiEnvironment env = request.getEnvironment();
			ApiOAuth oauth = env.getOauth();
			ApiConsumer consumer = env.getConsumer();

			Token consumerToken = new Token(consumer.getKey(), consumer.getSecret());

			String baseUrl = env.getScheme() + "://" + env.getHost();

			String requestEnpoint = baseUrl + oauth.getRequestEndpoint();
			String accessEndpoint = baseUrl + oauth.getAccessEndpoint();
			String authorizationEndpoint = baseUrl + oauth.getAuthorizationUrl();

			OAuthProvider provider = new OAuthProvider(requestEnpoint, accessEndpoint, authorizationEndpoint, consumerToken);

			Token access = provider.getAccessToken(request.getUsername(), request.getPassword());

			return new ApiUser(access.getToken(), access.getSecret());

		} catch (Exception e) {

			throw new RestClientException(e);
		}
	}
}
